<?php

namespace common\models;

use Yii;

/**
 * 系统常用工具函数集合
 */
class Tools
{
    //获取资源文件的位置
    public static $_assetsUrl;
    public static function getAssetsUrl() {
            if (self::$_assetsUrl === null){
                    $path = \Yii::$app->assetManager->publish( '@app/modules/assest')[1];
                    self::$_assetsUrl = substr($path, 1,strlen($path));
            }			
            return self::$_assetsUrl;
    }
    
    /**
     * 获取安全的参数，防MySql注入
     * @param string  $pi_strName $_GET或$_POST中要过滤的参数名称
     * @param string  $pi_Def     如果过滤失败的默认值
     * @param integer $pi_iType   0是过滤的int，1过滤的是string
     */
    public static function GetSafeParam($pi_strName, $pi_Def = "", $pi_iType = 1)
    {
        if ( isset($_GET[$pi_strName]) ){
            $t_Val = trim($_GET[$pi_strName]);
        }
        elseif ( isset($_POST[$pi_strName])){
            $t_Val = trim($_POST[$pi_strName]);
        }
        else{
            return $pi_Def;
        }
        return self::checkParams($t_Val, $pi_Def, $pi_iType);
    }

    /**
     * 处理传入参数，防mysql注入
     * @param int|string $t_Val     需要验证的参数
     * @param string $pi_Def        如果过滤失败的默认值
     * @param int $pi_iType         0是过滤的int，1过滤的是string
     * @return mixed|string
     */
    public static function checkParams($t_Val, $pi_Def = "", $pi_iType = 1)
    {
        // INT
        if ( 0 == $pi_iType)
        {
            if (is_numeric($t_Val))
                return $t_Val;
            else
                return $pi_Def;
        }

        // String
        $t_Val = str_replace("&", "&amp;",$t_Val);
        $t_Val = str_replace("<", "&lt;",$t_Val);
        $t_Val = str_replace(">", "&gt;",$t_Val);
        if ( get_magic_quotes_gpc() )
        {
            $t_Val = str_replace("\\\"", "&quot;",$t_Val);
            $t_Val = str_replace("\\''", "&#039;",$t_Val);
        }
        else
        {
            $t_Val = str_replace("\"", "&quot;",$t_Val);
            $t_Val = str_replace("'", "&#039;",$t_Val);
        }
        return $t_Val;
    }
	
    /*
     * 获取真实的IP地址
     * @return string 用户IP地址
    * */
    public static function getRealIpAddr()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
        {
                $ip=$_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
        {
                $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else if(!empty($_SERVER['REMOTE_ADDR']))
        {
                $ip=$_SERVER['REMOTE_ADDR'];
        }else{
                $ip='0.0.0.0';
        }

        $ipArr = explode(",", $ip);
        return $ipArr[0];
        //return $ip;
    }
	
    /*
     * 过滤所有的标点符号
     * */
    public static function filter_mark($text){
        if(trim($text)=='')return '';
        $text=preg_replace("/[[:punct:]\s]/",'',$text);
        $text=urlencode($text);
        $text=preg_replace("/(\s|%7E|%60|%21|%40|%23|%24|%25|%5E|%26|%27|%2A|%28|%29|%2B|%7C|%5C|%3D|\-|_|%5B|%5D|%7D|%7B|%3B|%22|%3A|%3F|%3E|%3C|%2C|\.|%2F|%A3%BF|%A1%B7|%A1%B6|%A1%A2|%A1%A3|%A3%AC|%7D|%A1%B0|%A3%BA|%A3%BB|%A1%AE|%A1%AF|%A1%B1|%A3%FC|%A3%BD|%A1%AA|%A3%A9|%A3%A8|%A1%AD|%A3%A4|%A1%A4|%A3%A1|%E3%80%82|%EF%BC%81|%EF%BC%8C|%EF%BC%9B|%EF%BC%9F|%EF%BC%9A|%E3%80%81|%E2%80%A6%E2%80%A6|%E2%80%9D|%E2%80%9C|%E2%80%98|%E2%80%99|%EF%BD%9E|%EF%BC%8E|%EF%BC%88)+/",'',$text);
        $text=urldecode($text);
        return trim($text);
    }

    /*
     * 生成商品编号
     * $param int $userid 用户ID
    * */
    public static function build_goods_no($userid)
    {
        return  time().$userid;
    }
    
    /*
     * 生成订单编号
     * $param int $userid 用户ID
    * */
    public static function build_order_no()
    {
        $micro = round(microtime(true)*100); //得到微秒的浮点数
        $rand = rand(1000, 9999);
        return  $micro.$rand;
    }
        
    /*
     * 按json格式输出信息
    * */
    public static function outputjson($output)
    {
        header('Content-type:text/json;charset=utf-8');
        echo json_encode($output);die;
    }

    /**
     * 按 jsonp 格式输出代码
     * @param  Class $output [description]
     * @return class         [description]
     */
    public static function outputjsonp($output)
    {
            header('Content-type:text/json;charset=utf-8');
            $callback = $_GET['callback'];
            echo $callback.'('.json_encode($output).')';
            exit;
    }
	
    /**
     * 根据参数区别输出信息格式
     *  format  == 1  return array
     *  format  == 2  输出json
     *  format  == 3  输出jsonp
     */
    public static function outputFormatByParameter($output, $format = 1){

        if ($format == 1) {
            return $output;
        }else if ($format == 2){
            self::outputjson($output);
        }else if ($format == 3){
            self::outputjsonp($output);
        }
    }
	
    /*
     * 对二维数组进行排序
    * */
    public static function array_sort($arr,$keys,$type='asc')
    {
            $keysvalue = $new_array = array();
            foreach ($arr as $k=>$v)
            {
                    $keysvalue[$k] = $v[$keys];
            }
            if($type == 'asc')
            {
                    asort($keysvalue);
            }
            else
            {
                    arsort($keysvalue);
            }
            reset($keysvalue);
            foreach ($keysvalue as $k=>$v)
            {
                    $new_array[$k] = $arr[$k];
            }
            return $new_array;
    }

        
    /**
     * 判断是否是webapp来源
     * @return boolean [description]
     */
    public static function isRefererWebApp(){  
            $useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';  
            $useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';     
            function CheckSubstrs($substrs,$text)
            {  
                    foreach($substrs as $substr)  
                    if(false!==strpos($text,$substr))
                    {  
                    return true;  
                    }  
                    return false;  
            }
             $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');
             $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');  

            $found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) ||  CheckSubstrs($mobile_token_list,$useragent);  

             if ($found_mobile)
             { 
                    return true;  
             }
             else
             {  
                    return false;  
             }  
    }
        
    /**
     * 对 MYSQL LIKE 的内容进行转义
     *
     * @access      public
     * @param       string      string  内容
     * @return      string
     */
    public static function mysql_like_quote($str)
    {
            return strtr($str, array("\\\\" => "\\\\\\\\", '_' => '\_', '%' => '\%', "\'" => "\\\\\'"));
    }
        
    /**
     * 加密算法
     * @param type $data
     * @param type $key
     * @return type
     * @author Youngshone
     */
    public static function encrypt($data, $key)
    {
        $key    =    md5($key);
        $x        =    0;
        $len    =    strlen($data);
        $l        =    strlen($key);
        $char = $str ="";
        
        for ($i = 0; $i < $len; $i++)
        {
            if ($x == $l) 
            {
                $x = 0;
            }
            $char .= $key{$x};
            $x++;
        }
        for ($i = 0; $i < $len; $i++)
        {
            $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
        }
        return base64_encode($str);
    }
    
    /**
     * 解密算法
     * @param type $str
     * @param type $key
     * @return type
     * @author Youngshone
     */
    public static function decrypt($data, $key)
    {
        $key = md5($key);
        $x = 0;
        $data = base64_decode($data);
        $len = strlen($data);
        $l = strlen($key);
        $char = $str = "";
        for ($i = 0; $i < $len; $i++)
        {
            if ($x == $l) 
            {
                $x = 0;
            }
            $char .= substr($key, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++)
        {
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
            {
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            }
            else
            {
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return $str;
    }
    
    
    public static function getUserCode($addtime,$userid){
        $key = Yii::$app->params['encrypt_key'];
        return self::encrypt($addtime."_".$userid, $key);
    }
    /**
     * 检测手机号码是否正确
     */
    public static function is_moblie($moblie)
    {
            return  preg_match("/^1[3-9]\d{9}$/", $moblie);
    }

    /**
     * 检测手机号码是否正确
     */
    public static function is_qq($qq){
        return preg_match("/^[1-9]\d{4,12}$/",$qq);
    }

    /**
     * 验证输入的邮件地址是否合法
     *
     * @access  public
     * @param   string      $email      需要验证的邮件地址
     * @return bool
     */
    public static function is_email($user_email)
    {
        $chars = "/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+\$/i";
        // $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";

        if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
        {
                if (preg_match($chars, $user_email))
                {
                        return true;
                }
                else
                {
                        return false;
                }
        }
        else
        {
                return false;
        }
    }
        
    /**
     * 真实姓名加****
     */
    public static function hideInfoByRealname($name){
        $len = mb_strlen($name,'utf-8');
        $result = "";
        if($len<=2){
            $result = mb_substr($name,0,1,'utf-8').'*';
        }else if($len>2){
            $result = mb_substr($name,0,1,'utf-8').str_repeat("*", $len-2).mb_substr($name,-1,1,'utf-8');
        }
        return $result;
    }

    /**
     * 网银账号加****
     */
    public static function hideInfoByBankno($bankno,$type = 1){
        // $type   1 是支付宝  2 是银行卡
        if ($type == 2) {
            // 显示前四位和后四位
            $str = preg_replace('/^(\d{4})\d+(\d{4})$/','\\1****\\2',$bankno);
            return $str;
        }else{
                return self::hideContactInfo($bankno);
        }
    }

    /**
     * 联系方式加****   （手机号、邮箱）
     */
    public static function hideContactInfo($str){
            // 如果是邮箱
            if (strpos($str,'@')) {
                    if (strpos($str,'@') < 5) {
                $start  = 1;
                $length = 1;
            }else{
                $start  = 2;
                $length = strpos($str,'@')-4;
            }
            $str = substr_replace($str,"******",$start,$length);
            }else{
            $str = substr_replace($str,"****",3,4);
            }
            return $str;
    }
        


    /**
     * 功能跳转页面
     */
    public static function get_show_msg($url, $show = '操作已成功！',$type=0,$wait=3) {
        if($type==1){
               $str='<p class="success">恭喜^_^!~'.$show.'</p>';
        }else{
               $str=' <p class="error">Sorry!~'.$show.'</p>';
        }
        $msg = '<!DOCTYPE html><html lang="en-US">
                       <head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge">
                       <title>操作提示</title>
                       <style type="text/css">
                       *{ padding: 0; margin: 0; }
                       body{ background: #fff; font-family: \'微软雅黑\'; color: #333; font-size: 16px; }
                       .system-message{ width:500px;height:100px; margin:auto;border:6px solid #999;text-align:center; position:relative;top:50px;}
                       .system-message legend{font-size:24px;font-weight:bold;color:#999;margin:auto;width:100px;}
                       .system-message h1{ font-size: 100px; font-weight: normal; line-height: 120px; margin-bottom: 12px; }
                       .system-message .jump{ padding-right:10px;height:25px;line-height:25px;font-size:14px;position:absolute;bottom:0px;left:0px;background-color:#e6e6e1 ; display:block;width:490px;text-align:right;}
                       .system-message .jump a{ color: #333;}
                       .system-message .success,.system-message .error{ line-height: 1.8em; font-size: 15px }
                       .system-message .detail{ font-size: 12px; line-height: 20px; margin-top: 12px; display:none}
                       </style>
                       </head>
                       <body>
                       <fieldset class="system-message">
                           <legend>操作提示</legend>
                           <div style="text-align:left;padding-left:10px;height:75px;width:490px;  ">
                               '.$str.'				        
                               <p class="detail"></p>

                           </div>
                           <p class="jump">'. (!$url ? '页面自动 <a id="href" href="javascript:void(0)" onclick="window.history.go(-1)">跳转</a> 等待时间： <b id="wait">' . $wait . '</b>' : '页面自动 <a id="href" href="' . $url . '">跳转</a> 等待时间： <b id="wait">' . $wait . '</b>') . 
                           '</p>
                       </fieldset>
                       <script type="text/javascript">
                       (function(){
                       var wait = document.getElementById(\'wait\'),href = document.getElementById(\'href\').href;
                       totaltime=parseInt(wait.innerHTML);
                       var interval = setInterval(function(){
                           var time = --totaltime;
                               wait.innerHTML=""+time;
                           if(time === 0) {' . (!$url ? 'window.history.go(-1);' : 'location.href = href;') .
                               'clearInterval(interval);
                           };
                       }, 1000);
                       })();

                       </script>
                       </body>
                       </html>';
        echo $msg;
        exit ();
    }
        
    /**自定义链接静态链接的分页方法
     */
    public static function showPager($link,&$page_no,$page_size,$row_count,$keywords=''){
        $url="";
        $params="";
        if($keywords !==''){
                $keywords='?wd='.$keywords;
        }
        if($link != ""){
                $pos = strpos($link,"?");

                if($pos ===false ){
                        $url = $link;
                }else{
                        $url=substr($link,0,$pos);
                        $params=substr($link,$pos+1);
                }
        }

        $navibar = "<div><ul class=\"pagination pull-right\">";
        $offset=3;//self::OFFSET;
        //$page_size=10;
        $total_page=$row_count%$page_size==0?$row_count/$page_size:ceil($row_count/$page_size);

        $page_no=$page_no<1?1:$page_no;
        $page_no=$page_no>($total_page)?($total_page):$page_no;
        if ($page_no > 1){
                $navibar .= "<li><a href=\"{$url}-1$keywords\">首页</a></li>\n <li><a href=\"$url-".($page_no-1)."$keywords\">上一页</a></li>\n";
        }
        /**** 显示页数 分页栏显示11页，前5条...当前页...后5条 *****/
        $start_page = $page_no -$offset;
        $end_page =$page_no+$offset;
        if($start_page<1){
                $start_page=1;
        }
        if($end_page>$total_page){
                $end_page=$total_page;
        }
        for($i=$start_page;$i<=$end_page;$i++){
                if($i==$page_no){
                        $navibar.= "<li class='active'><a href=\"javascript:;\">$i</a></li>";
                }else{
                        $navibar.= "<li><a href=\" {$url}-{$i}$keywords \">$i</a></li>";
                }
        }

        if ($page_no < $total_page){
                $navibar .= "<li><a href=\"$url-".($page_no+1)."$keywords\">下一页</a></li>\n <li><a href=\"{$url}-{$total_page}$keywords\">末页</a></li>\n ";
        }
        if($total_page>0){
                $navibar.="<li><a>".$page_no ."/". $total_page."</a></li>";
        }
        $navibar.="<li><a>共".$row_count."条</a></li>";
        $jump ="";
        //$jump ="<li><form action='$url' method='GET' name='jumpForm'><input type='text' name='page_no' value='$page_no'></form></li>";
        //$navibar.=$jump;
        $navibar.="</ul></div>";

        return $navibar;
    }

    /**
     * @description 生成分页
     *
     */
    public static function showNewPager($link, &$page_no, $page_size, $row_count, $keywords='', $selectParams = array()){
		$url = "";
		$params = "";
        if(!empty($keywords)) {
            $selectParams['wd'] = htmlspecialchars($keywords);
        }
        if(!empty($selectParams)) {
            $params = "?" . http_build_query($selectParams);
        }else{
            $params = "";
        }
		if($link != ""){
			$pos = strpos($link,"?");
			if($pos ===false ){
				$url = $link;
			}else{
				$url=substr($link,0,$pos);
			}
		}
		$navibar    = "<div><ul class=\"pagination pull-right\">";
		$len        = 10 ;//self::OFFSET;
        $margin     = ceil($len / 2);
		//$page_size=10;
		$total_page = ($row_count % $page_size == 0 ) ? ($row_count / $page_size) : ceil($row_count / $page_size);
	
		$page_no    = $page_no < 1 ? 1 : $page_no;
		$page_no    = $page_no > $total_page ? $total_page : $page_no;
		if ($page_no > 1){
			$navibar .= "<li><a href=\"{$url}-1$params\">首页</a></li>\n <li><a href=\"$url-".($page_no-1)."$params\">上一页</a></li>\n";
		}
        
        if($page_no <= $margin) {
            $start_page = 1;

            if($total_page > $len) {
                $end_page = $len; 
            }else{
                $end_page = $total_page;
            }
        } else {
            $start_page = $page_no - $margin;
            if(($total_page - $page_no) > ($margin - 1)) {
                $end_page = $page_no + ($margin - 1); 
            }else{
                $end_page = $total_page;
            }
        }
        for( $i = $start_page; $i <= $end_page; $i++){
            if($i == $page_no){
                    $navibar.= "<li class='active'><a href=\"javascript:;\">$i</a></li>";
            }else{
                    $navibar.= "<li><a href=\" {$url}-{$i}$params \">$i</a></li>";
            }
        }
	
        if ($page_no < $total_page){
            $navibar .= "<li><a href=\"$url-".($page_no+1)."$params\">下一页</a></li>\n <li><a href=\"{$url}-{$total_page}$params\">末页</a></li>\n ";
        }

        if($total_page > 0){
            $navibar.="<li><a>".$page_no ."/". $total_page."</a></li>";
            $navibar.="<li class=\"jumpto\"><span class=\"jumpto-label\">跳转到：</span><em class=\"input-jump-url-wrapper\"><input type=\"text\" id=\"input-jump-url\" class=\"input-jump-url\" /></em> <button class=\"btn-jump-url\" tourl=\"{$url}-[[]]{$params}\" totalpage=\"{$total_page}\">GO</button></li>";
        }
        $jump ="";
        $navibar.="</ul></div>";
	
        return $navibar;
    }

    /**
     * @description 生成分页
     *
     */
    public static function showCmPager(&$page_no, $page_size, $row_count,$condition){
        $url = trim($_SERVER['REQUEST_URI']);
        $arrUrl = parse_url($url); 
//        echo print_r($arrUrl);exit;
//        if(!isset($arrUrl['query'])) {
//            $url = $arrUrl['path'] . "?page_no=";
//        }else{
//            parse_str($arrUrl['query'], $arrQuery);
//            unset($arrQuery['page_no']);
//            $arrQuery['page_no'] = "";
//            $url = $arrUrl['path'] . "?page_no=$page_no&" . http_build_query($condition);
//        }
        $url = $arrUrl['path'] . "?".http_build_query($condition)."&page_no=";
		$navibar    = "<div><ul class=\"pagination pull-right\">";
		$len        = 10 ;//self::OFFSET;
        $margin     = ceil($len / 2);
		//$page_size=10;
		$total_page = ($row_count % $page_size == 0 ) ? ($row_count / $page_size) : ceil($row_count / $page_size);
	
		$page_no    = $page_no < 1 ? 1 : $page_no;
		$page_no    = $page_no > $total_page ? $total_page : $page_no;
		if ($page_no > 1){
			$navibar .= "<li><a href=\"{$url}1\">首页</a></li>\n <li><a href=\"$url".($page_no-1)."\">上一页</a></li>\n";
		}
        
        if($page_no <= $margin) {
            $start_page = 1;

            if($total_page > $len) {
                $end_page = $len; 
            }else{
                $end_page = $total_page;
            }
        } else {
            $start_page = $page_no - $margin;

            if(($total_page - $page_no) > ($margin - 1)) {
                $end_page = $page_no + ($margin - 1); 
            }else{
                $end_page = $total_page;
            }
        }
        

		for( $i = $start_page; $i <= $end_page; $i++){
			if($i == $page_no){
				$navibar.= "<li class='active'><a href=\"javascript:;\">$i</a></li>";
			}else{
				$navibar.= "<li><a href=\" {$url}{$i} \">$i</a></li>";
			}
		}
	
		if ($page_no < $total_page){
			$navibar .= "<li><a href=\"$url".($page_no+1)."\">下一页</a></li>\n <li><a href=\"{$url}{$total_page}\">末页</a></li>\n ";
        }
		if($total_page > 0){
			$navibar.="<li><a>".$page_no ."/". $total_page."</a></li>";
            $navibar.="<li class=\"jumpto\"><span class=\"jumpto-label\">跳转到：</span><em class=\"input-jump-url-wrapper\"><input type=\"text\" id=\"input-jump-url\" class=\"input-jump-url\"  /></em> <button class=\"btn-jump-url\" tourl=\"{$url}\" totalpage=\"{$total_page}\">GO</button></li>";
		}
		//$navibar.="<li><a>每页显示".$row_count."条</a></li>";
		$jump ="";
		//$jump ="<li><form action='$url' method='GET' name='jumpForm'><input type='text' name='page_no' value='$page_no'></form></li>";
		//$navibar.=$jump;
		$navibar.="</ul></div>";
	
		return $navibar;
    }

    /*
     * 按json格式输出错误信息
    * */
    public static function outputErrorcodeJson($codes,$data=[],$msg='')
    {
            header('Content-type:text/json;charset=utf-8');
            $errorCode['errcode'] = $codes;
            $errorCode['msg'] = $msg ? $msg : ErrorCodes::$ERROR_MSG[$codes];
            $errorCode['data'] = $data;
            echo json_encode($errorCode);
    }

    /*
     * 按json格式输出错误信息
    * */
    public static function outputErrorcodeJsonObj($codes,$data=[])
    {
        header('Content-type:text/json;charset=utf-8');
        $errorCode['errcode'] = $codes;
        $errorCode['msg'] = ErrorCodes::$ERROR_MSG[$codes];
        if(empty($data)){
            $data = new stdClass();
        }
        $errorCode['data'] = $data;
        return json_encode($errorCode);
    }

    /**
     * 按Array格式输出错误信息
     */
            public static function outputErrorcodeArray($codes,$data=[])
    {
            $errorCode['errcode'] = $codes;
            $errorCode['msg'] = ErrorCodes::$ERROR_MSG[$codes];
            $errorCode['data'] = $data;
            return $errorCode;
    }

    /**
     * 未登录拼接url
     */
    public static function isGuestJointUrl($url = NULL){
            $loginurl = "/siteauth/auth/login?";
            $params=array(
                            'returnurl'=>\Yii::$app->request->hostInfo . ($url ? $url : \Yii::$app->request->url)
                    );

            return $loginurl.http_build_query($params);
    }

    /**
     * 验证强度
     * @param string $str
     */
    public static function passwordStrength($str){
        $score = 0;
        //有数字
        if(preg_match("/[0-9]+/",$str)){
                $score ++; 
        }
        //有小写字母
        if(preg_match("/[a-z]+/",$str)){
                $score ++; 
        }
        //有大写字母
        if(preg_match("/[A-Z]+/",$str)){
                $score ++; 
        }
        //有符号
        if(preg_match("/[`|~|!|@|#|$|%|^|&|*|(|)|-|+|=|\/|\\|\[|\]|\{|\}|?|.|,|\|]+/",$str)){
                $score++; 
        }
        //6位以下的强度都为1
        if(mb_strlen($str,'utf-8') < 6){
                $score = 1;
        }
        //12位以下三类或四类强度为3
        if(mb_strlen($str,'utf-8') < 12 && $score >= 3){
                $score = 3;
        }
        //12位以上三类或四类强度为4
        if(mb_strlen($str,'utf-8') >= 12 && $score >= 3){
                $score = 4;
        }
        return $score;
    }

    /**
     * 将对象转换为数组
     * @param object $object
     */
    public static function objectToArray($object){
        $array = [];
        foreach($object as $k => $v){
            $array[$k] = $v;
        }
        return $array;
    }
    
    /**
    * PHP发送Json对象数据
    *
    * @param $url 请求url
    * @param $jsonStr 发送的json字符串
    */
    public static function curl_post_https($url,$data){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl,CURLOPT_HTTPHEADER,array("Expect:"));
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);              // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);              // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 3000); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    // $url 请求地址
    // $jsonarr 参数数组
    // $headers 头部设置信息
    // $headers = ['merchantNo:123','encryptKey:jdshkjhk']
    public static function requestPostJson($url='',$jsonarr=[],$headers=[]){
        $jsonStr = '{}';
        if (!empty($jsonarr)) {
            $jsonStr = json_encode($jsonarr);
        }
        $head = array_merge(['Content-Type: application/json; charset=utf-8','Content-Length: ' . strlen($jsonStr)],$headers);
//        echo "<pre>";
//        print_r($headers);exit;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $head);

        $response = curl_exec($ch);
        // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $response;
    }
    
    //url发起网络请求 param为参数拼接string
    public static function requestPost($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        
        return $data;
    }
    
    public static function curl_get($url){
        $header = array(
            'Accept: application/json',
         );
         $curl = curl_init();
         //设置抓取的url
         curl_setopt($curl, CURLOPT_URL, $url);
         //设置头文件的信息作为数据流输出
         curl_setopt($curl, CURLOPT_HEADER, 0);
         // 超时设置,以秒为单位
         curl_setopt($curl, CURLOPT_TIMEOUT, 1);

         // 超时设置，以毫秒为单位
         // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

         // 设置请求头
         curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
         //设置获取的信息以文件流的形式返回，而不是直接输出。
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
         //执行命令
         $data = curl_exec($curl);

         // 显示错误信息
         if (curl_error($curl)) {
             print "Error: " . curl_error($curl);
         } else {
             // 打印返回的内容
             
             curl_close($curl);
             return $data;
         }
     }
	
    /*
     * 根据ip获取归属地信息
     * @return string 用户地址信息
     * 2018-08-04
    * */
    public static function getRealAddrToIp($ip)
    {
            if (!empty($ip))   //check ip from share internet
            {
                    $ip = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);
                    var_dump($ip);exit;
                    $ip = json_decode($ip,true);
                    $ip = !empty($ip['data']['city']) ? ' [归属地] ' . $ip['data']['country'].$ip['data']['area'].$ip['data']['region'].$ip['data']['city'].' ['.$ip['data']['isp'].']' : '';
            }else{
                    $ip='';
            }
            return $ip;
    }

    /*
     * 根据身份证号获取年龄
     * @return string 用户地址信息
     * 2018-08-04
     * */
    public static function getAgeByID($id){
        //过了这年的生日才算多了1周岁
        if(empty($id)) return '';
        $date=strtotime(substr($id,6,8));
        //获得出生年月日的时间戳
        $today=strtotime('today');
        //获得今日的时间戳 111cn.net
        $diff=floor(($today-$date)/86400/365);
        //得到两个日期相差的大体年数

        //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
        $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;

        return $age;
    }
    //计算时间
    public static function calculateTimelong($time){
        $this_year = date('Y', time());
        $time_year = date('Y', $time);
        $distance = time()-$time;
        $timelong = "";
        if($distance<=60){
            $timelong = $distance."秒前";
        }elseif($distance>60 && $distance<=60*60){
            $timelong = floor($distance/60)."分钟前";
        }elseif($distance>60*60 && $distance<= 60*60*24){
            $timelong = floor($distance/3600)."小时前";
        }elseif($distance>60*60*24){
            $timelong = $time_year == $this_year ? date('m-d H:i:s',$time) : date('Y-m-d H:i:s',$time);
        }
        return $timelong;
    }
    
    //获取汉字的首字母
    public static function getFirstCharters($str){
        if (empty($str)) {
            return '';
        }
        //取出参数字符串中的首个字符
        $temp_str = substr($str,0,1);
        if(ord($temp_str) > 127){
            $str = substr($str,0,3);
        }else{
            $str = $temp_str;
            $fchar = ord($str{0});
            if ($fchar >= ord('A') && $fchar <= ord('z')){
                return strtoupper($temp_str);
            }else{
                return null;
            }
        }
        $s1 = iconv('UTF-8', 'gb2312//IGNORE', $str);
        if(empty($s1)){
            return null;
        }
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        if(empty($s2)){
            return null;
        }
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 && $asc <= -20284)
            return 'A';
        if ($asc >= -20283 && $asc <= -19776)
            return 'B';
        if ($asc >= -19775 && $asc <= -19219)
            return 'C';
        if ($asc >= -19218 && $asc <= -18711)
            return 'D';
        if ($asc >= -18710 && $asc <= -18527)
            return 'E';
        if ($asc >= -18526 && $asc <= -18240)
            return 'F';
        if ($asc >= -18239 && $asc <= -17923)
            return 'G';
        if ($asc >= -17922 && $asc <= -17418)
            return 'H';
        if ($asc >= -17417 && $asc <= -16475)
            return 'J';
        if ($asc >= -16474 && $asc <= -16213)
            return 'K';
        if ($asc >= -16212 && $asc <= -15641)
            return 'L';
        if ($asc >= -15640 && $asc <= -15166)
            return 'M';
        if ($asc >= -15165 && $asc <= -14923)
            return 'N';
        if ($asc >= -14922 && $asc <= -14915)
            return 'O';
        if ($asc >= -14914 && $asc <= -14631)
            return 'P';
        if ($asc >= -14630 && $asc <= -14150)
            return 'Q';
        if ($asc >= -14149 && $asc <= -14091)
            return 'R';
        if ($asc >= -14090 && $asc <= -13319)
            return 'S';
        if ($asc >= -13318 && $asc <= -12839)
            return 'T';
        if ($asc >= -12838 && $asc <= -12557)
            return 'W';
        if ($asc >= -12556 && $asc <= -11848)
            return 'X';
        if ($asc >= -11847 && $asc <= -11056)
            return 'Y';
        if ($asc >= -11055 && $asc <= -10247)
            return 'Z';
        return self::rare_words($asc);
    }
    //百家姓中的生僻字
    public static function rare_words($asc=''){
        $rare_arr = array(
            -3652=>array('word'=>"窦",'first_char'=>'D'),
            -8503=>array('word'=>"奚",'first_char'=>'X'),
            -9286=>array('word'=>"酆",'first_char'=>'F'),
            -7761=>array('word'=>"岑",'first_char'=>'C'),
            -5128=>array('word'=>"滕",'first_char'=>'T'),
            -9479=>array('word'=>"邬",'first_char'=>'W'),
            -5456=>array('word'=>"臧",'first_char'=>'Z'),
            -7223=>array('word'=>"闵",'first_char'=>'M'),
            -2877=>array('word'=>"裘",'first_char'=>'Q'),
            -6191=>array('word'=>"缪",'first_char'=>'M'),
            -5414=>array('word'=>"贲",'first_char'=>'B'),
            -4102=>array('word'=>"嵇",'first_char'=>'J'),
            -8969=>array('word'=>"荀",'first_char'=>'X'),
            -4938=>array('word'=>"於",'first_char'=>'Y'),
            -9017=>array('word'=>"芮",'first_char'=>'R'),
            -2848=>array('word'=>"羿",'first_char'=>'Y'),
            -9477=>array('word'=>"邴",'first_char'=>'B'),
            -9485=>array('word'=>"隗",'first_char'=>'K'),
            -6731=>array('word'=>"宓",'first_char'=>'M'),
            -9299=>array('word'=>"郗",'first_char'=>'X'),
            -5905=>array('word'=>"栾",'first_char'=>'L'),
            -4393=>array('word'=>"钭",'first_char'=>'T'),
            -9300=>array('word'=>"郜",'first_char'=>'G'),
            -8706=>array('word'=>"蔺",'first_char'=>'L'),
            -3613=>array('word'=>"胥",'first_char'=>'X'),
            -8777=>array('word'=>"莘",'first_char'=>'S'),
            -6708=>array('word'=>"逄",'first_char'=>'P'),
            -9302=>array('word'=>"郦",'first_char'=>'L'),
            -5965=>array('word'=>"璩",'first_char'=>'Q'),
            -6745=>array('word'=>"濮",'first_char'=>'P'),
            -4888=>array('word'=>"扈",'first_char'=>'H'),
            -9309=>array('word'=>"郏",'first_char'=>'J'),
            -5428=>array('word'=>"晏",'first_char'=>'Y'),
            -2849=>array('word'=>"暨",'first_char'=>'J'),
            -7206=>array('word'=>"阙",'first_char'=>'Q'),
            -4945=>array('word'=>"殳",'first_char'=>'S'),
            -9753=>array('word'=>"夔",'first_char'=>'K'),
            -10041=>array('word'=>"厍",'first_char'=>'S'),
            -5429=>array('word'=>"晁",'first_char'=>'C'),
            -2396=>array('word'=>"訾",'first_char'=>'Z'),
            -7205=>array('word'=>"阚",'first_char'=>'K'),
            -10049=>array('word'=>"乜",'first_char'=>'N'),
            -10015=>array('word'=>"蒯",'first_char'=>'K'),
            -3133=>array('word'=>"竺",'first_char'=>'Z'),
            -6698=>array('word'=>"逯",'first_char'=>'L'),
            -9799=>array('word'=>"俟",'first_char'=>'Q'),
            -6749=>array('word'=>"澹",'first_char'=>'T'),
            -7220=>array('word'=>"闾",'first_char'=>'L'),
            -10047=>array('word'=>"亓",'first_char'=>'Q'),
            -10005=>array('word'=>"仉",'first_char'=>'Z'),
            -3417=>array('word'=>"颛",'first_char'=>'Z'),
            -6431=>array('word'=>"驷",'first_char'=>'S'),
            -7226=>array('word'=>"闫",'first_char'=>'Y'),
            -9293=>array('word'=>"鄢",'first_char'=>'Y'),
            -6205=>array('word'=>"缑",'first_char'=>'G'),
            -9764=>array('word'=>"佘",'first_char'=>'S'),
            -9818=>array('word'=>"佴",'first_char'=>'N'),
            -9509=>array('word'=>"谯",'first_char'=>'Q'),
            -3122=>array('word'=>"笪",'first_char'=>'D'),
            -9823=>array('word'=>"佟",'first_char'=>'T'),
        );
        if(array_key_exists($asc, $rare_arr) && $rare_arr[$asc]['first_char']){
            return $rare_arr[$asc]['first_char'] ;
        }else{
            return null;
        }
    }
}
